# 设置项目路径
$PROJECT_PATH = Get-Location

# 定义 APK 文件路径
$APK_SOURCE_PATH = Join-Path $PROJECT_PATH "build\app\outputs\flutter-apk\app-release.apk"

# 添加 build-tools 路径到环境变量
$env:PATH += ";$env:USERPROFILE\AppData\Local\Android\Sdk\build-tools\36.0.0"

# 构建 APK
Write-Host "Building APK for Android ARM64..."
flutter build apk --target-platform android-arm64 --release
if ($LASTEXITCODE -ne 0)
{
    Write-Host "Build failed, please check the error messages above."
    exit 1
}

# 检查 APK 是否生成
if (-Not (Test-Path $APK_SOURCE_PATH))
{
    Write-Host "Build failed, APK not found at $APK_SOURCE_PATH."
    exit 1
}

# 读取 APK 信息
$APK_PACKAGE_NAME = & "aapt" dump badging $APK_SOURCE_PATH | Select-String -Pattern "package: name='([^']+)'" | ForEach-Object { $_.Matches.Groups[1].Value }
$APK_VERSION_CODE = & "aapt" dump badging $APK_SOURCE_PATH | Select-String -Pattern "versionCode='(\d+)'" | ForEach-Object { $_.Matches.Groups[1].Value }
$APK_VERSION_NAME = & "aapt" dump badging $APK_SOURCE_PATH | Select-String -Pattern "versionName='([^']+)'" | ForEach-Object { $_.Matches.Groups[1].Value }

# 重命名 APK
$NEW_FILE_NAME = "$APK_PACKAGE_NAME-v$APK_VERSION_CODE($APK_VERSION_NAME)-release.apk"
$APK_TARGET_PATH = Join-Path (Split-Path $APK_SOURCE_PATH -Parent) $NEW_FILE_NAME
Move-Item -Path $APK_SOURCE_PATH -Destination $APK_TARGET_PATH -Force
if ($LASTEXITCODE -ne 0)
{
    Write-Host "Failed to move APK to target path."
    exit 1
}

Write-Host "APK build and rename completed successfully."
Write-Host "APK file is located at: $APK_TARGET_PATH"
exit 0
